﻿using BPMS.Business;
using BPMS.Entity;
using BPMS.IBusiness;
using BPMS.Service;
using DotNet.Kernel;
using DotNet.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BPMS.MVC.Controllers
{
    public class FrameController : Controller
    {
        BPMS_UserIBLL bpms_useribll = new BPMS_UserBLL();
        BPMS_User bpms_user = new BPMS_User();
        BPMS_OrganizationIBLL bpms_organizationibll = new BPMS_OrganizationBLL();
        BPMS_Organization bpms_organization = new BPMS_Organization();
        BPMS_SysLogIBLL bpms_syslogibll = new BPMS_SysLogBLL();
        BPMS_IPBlacklistIBLL bpms_ipblacklistibll = new BPMS_IPBlacklistBLL();
        IPScanerHelper objScan = new IPScanerHelper();

        #region 页面路由 Login()、MainIndex()、HomeIndex()
        /// <summary>
        /// 初始化页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 后台首页-手风琴
        /// </summary>
        /// <returns></returns>
        public ActionResult MainIndex()
        {
            ViewBag.UserName = SessionHelper.GetSessionUser().UserName + "[" + SessionHelper.GetSessionUser().Code + "]";//操作员
            ViewBag.DepartmentName = SessionHelper.GetSessionUser().DepartmentName; ;//所在部门
            return View();
        }
        /// <summary>
        /// 后台首页-手风琴 - 子页面
        /// </summary>
        /// <returns></returns>
        public ActionResult HomeIndex()
        {
            return View();
        }
        #endregion

        #region 生成验证码 ActionResult VerifyCode()
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyCode()
        {
            int codeW = 80;
            int codeH = 22;
            int fontSize = 16;
            string chkCode = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session
            Session["dt_session_code"] = chkCode;
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 1; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, (float)0);
            }
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return File(ms.ToArray(), @"image/Gif");
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }
        #endregion

        #region 登录验证 ActionResult CheckUserLogin()
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckUserLogin()
        {
            string Msg = "";
            string Account = Request["Account"];                    //账户
            string Pwd = Request["Pwd"];                            //密码
            string code = Request["code"];                          //验证码
            try
            {
                string IPAddress = RequestHelper.GetIPAddress();
                objScan.IP = IPAddress;
                objScan.DataPath = Server.MapPath("/Themes/IPScaner/QQWry.Dat");
                string IPAddressName = objScan.IPLocation();
                if (code.ToLower() != Session["dt_session_code"].ToString().ToLower())
                {
                    Msg = "1";//验证码输入不正确
                }
                else
                {
                    //系统管理
                    if (Account == ConfigHelper.GetValue("CurrentUserName") && Md5Helper.MD5(Pwd, 32) == ConfigHelper.GetValue("CurrentPassword"))
                    {
                        SessionUser user = new SessionUser();
                        user.UserId = "System";
                        user.Account = "System";
                        user.UserName = "超级管理员";
                        user.Gender = "男";
                        user.Password = bpms_user.Password;
                        user.Code = "System";
                        user.DepartmentId = "超级管理员";
                        user.DepartmentName = "超级管理员";
                        SessionHelper.AddSessionUser(user);
                        Msg = "3";//验证成功
                        bpms_syslogibll.AddSysLoginLog(bpms_user.Account, "登录成功", IPAddress, IPAddressName);
                    }
                    else
                    {
                        #region 验证
                        bpms_ipblacklistibll.TheIpIsRange(IPAddress);
                        string outmsg;
                        bpms_user = bpms_useribll.UserLogin(Account.Trim(), Pwd.Trim(), out outmsg);
                        if (outmsg != "-1")
                        {
                            if (outmsg == "succeed")
                            {
                                if (bpms_user.Enabled == 1)
                                {
                                    if (Islogin(Account.Trim()))
                                    {
                                        string DepartmentName = "";
                                        bpms_organization = bpms_organizationibll.GetEntity(bpms_user.DepartmentId);
                                        if (bpms_organization != null)
                                        {
                                            DepartmentName = bpms_organization.FullName;
                                        }
                                        SessionUser user = new SessionUser();
                                        user.UserId = bpms_user.UserId;
                                        user.Account = bpms_user.Account;
                                        user.UserName = bpms_user.RealName;
                                        user.Gender = bpms_user.Gender;
                                        user.Password = bpms_user.Password;
                                        user.Code = bpms_user.Code;
                                        user.Secretkey = bpms_user.Secretkey;
                                        user.DepartmentId = bpms_user.DepartmentId;
                                        user.DepartmentName = DepartmentName;
                                        user.RoleId = bpms_user.RoleId;
                                        SessionHelper.AddSessionUser(user);
                                        Msg = "3";//验证成功
                                        bpms_syslogibll.AddSysLoginLog(bpms_user.Account, "登录成功", IPAddress, IPAddressName);
                                    }
                                    else
                                    {
                                        //该用户已经登录，不允许重复登录
                                        return Content("6");
                                    }
                                }
                                else
                                {
                                    Msg = "2";//账户锁定
                                    bpms_syslogibll.AddSysLoginLog(bpms_user.Account, "账户锁定", IPAddress, IPAddressName);
                                }
                            }
                            else
                            {
                                Msg = "4";//账户或者密码有错误
                                bpms_syslogibll.AddSysLoginLog(bpms_user.Account, "登录失败", IPAddress, IPAddressName);
                            }
                        }
                        else
                        {
                            Msg = DbResultMsg.ReturnMsg;//服务连接不上
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
            }
            return Content(Msg);
        }
        /// <summary>
        /// 同账号不允许重复登录
        /// </summary>
        /// <param name="Account">账户</param>
        /// <returns></returns>
        public bool Islogin(string Account)
        {
            if (!CommonHelper.GetBool(ConfigHelper.GetValue("CheckOnLine")))
            {
                return true;
            }
            //将Session转换为Arraylist数组
            ArrayList list = Session["CheckOnLine_List"] as ArrayList;
            if (list == null)
            {
                list = new ArrayList();
            }
            for (int i = 0; i < list.Count; i++)
            {
                if (Account == (list[i] as string))
                {
                    //已经登录了，提示错误信息 
                    return false; ;
                }
            }
            //将用户信息添加到list数组中
            list.Add(Account);
            //将数组放入Session
            Session.Add("CheckOnLine_List", list);
            return true;
        }
        #endregion

        #region 加载模块菜单数据 ActionResult LoadMenu()
        /// <summary>
        /// 加载模块菜单数据
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadMenu()
        {
            string UserId = SessionHelper.GetSessionUser().UserId;
            IList list = (IList)StorePermission.Instance.GetModulePermission(UserId);
            return Content(JsonHelper.DropToJson<BPMS_ModulePermission>(list, "JSON"));
        }
        #endregion

        #region void SetSystemId()
        /// <summary>
        /// //模块ID、访问模块
        /// </summary>
        public void SetSystemId()
        {
            string UserId = SessionHelper.GetSessionUser().UserId;
            string SystemId = Request["SystemId"];                    //模块ID
            List<BPMS_ModulePermission> Modulelist = IListHelper.IListToList<BPMS_ModulePermission>((IList)StorePermission.Instance.GetModulePermission(UserId)).FindAll(t => t.MenuId == SystemId);
            foreach (BPMS_ModulePermission entity in Modulelist)
            {
                BPMS_SysLogDAL.Instance.AddVisitLog(UserId, SessionHelper.GetSessionUser().UserName, entity.FullName, "URL:" + entity.NavigateUrl);
                break;
            }
            //写入Session
            Session["SystemId"] = SystemId;
        }
        #endregion

        #region 安全退出 OutLogin();
        /// <summary>
        /// 安全退出
        /// </summary>
        /// <returns></returns>
        public ActionResult OutLogin()
        {
            string UserId = SessionHelper.GetSessionUser().UserId;
            CacheHelper.RemoveAllCache("Module" + UserId);
            CacheHelper.RemoveAllCache("Button" + UserId);
            CacheHelper.RemoveAllCache("Data" + UserId);
            Session.Abandon();  //取消当前会话
            Session.Clear();    //清除当前浏览器所以Session
            return Content("1");
        }
        #endregion


    }
}
